package com.xiaohe66.web.infrastructure.mybatis.im.repository;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaohe66.common.value.Paging;
import com.xiaohe66.web.domain.account.value.AccountId;
import com.xiaohe66.web.domain.im.agg.Message;
import com.xiaohe66.web.domain.im.repository.MessageRepository;
import com.xiaohe66.web.domain.im.value.MessageId;
import com.xiaohe66.web.domain.im.value.MessageUnread;
import com.xiaohe66.web.infrastructure.mybatis.im.convert.MessageDoConverter;
import com.xiaohe66.web.infrastructure.mybatis.im.mapper.MessageMapper;
import com.xiaohe66.web.infrastructure.mybatis.im.model.MessageDo;
import com.xiaohe66.web.infrastructure.mybatis.im.model.MessageUnreadDo;
import com.xiaohe66.web.integration.AbstractMybatisService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author xiaohe
 * @since 2023-08-09 16:00
 */
@Repository
@Slf4j
@RequiredArgsConstructor
public class MessageRepositoryImpl
        extends AbstractMybatisService<MessageDoConverter, MessageMapper, MessageDo, Message, MessageId>
        implements MessageRepository {

    @Override
    public List<MessageUnread> countByAccountIdUnread(AccountId accountId) {

        List<MessageUnreadDo> list = baseMapper.countByAccountIdUnread(accountId.getValue());

        return dataConverter.toEntity(list);
    }

    @Override
    public List<Message> listByAccount(AccountId accountId, MessageId beforeId) {

        LambdaQueryWrapper<MessageDo> queryWrapper = new LambdaQueryWrapper<MessageDo>()
                .eq(MessageDo::getAccountId, accountId.getValue())
                .gt(MessageDo::getId, beforeId.getValue())
                .orderByDesc(MessageDo::getId);

        List<MessageDo> list = list(queryWrapper);

        return dataConverter.toAgg(list);
    }

    @Override
    public List<Message> pageByAccountId(Paging paging, AccountId accountId) {

        LambdaQueryWrapper<MessageDo> queryWrapper = new LambdaQueryWrapper<MessageDo>()
                .eq(MessageDo::getAccountId, accountId.getValue())
                .orderByDesc(MessageDo::getId)
                .last(paging.toLimit());

        List<MessageDo> list = list(queryWrapper);

        return dataConverter.toAgg(list);
    }

    @Override
    public List<Message> pageOfAccountId(Paging paging, AccountId createId, AccountId accountId) {

        List<MessageDo> messageDos = baseMapper.pageOfAccountId(paging, createId.getValue(), accountId.getValue());

        return dataConverter.toAgg(messageDos);
    }
}
